package com.niodata.dp.expression.function.date;

import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorObject;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public class DateParseFunction extends AbstractFunction {

  @Override
  public String getName() {
    return "date.parse";
  }

  public AviatorObject call(Map<String, Object> env, AviatorObject src, AviatorObject format) {
    String fmt = FunctionUtils.getStringValue(format, env);
    String source = FunctionUtils.getStringValue(src, env);
    SimpleDateFormat sdf = new SimpleDateFormat(fmt);
    try {
      Date date = sdf.parse(source);
      return FunctionUtils.wrapReturn(date);
    } catch (ParseException e) {
      throw new RuntimeException(e);
    }
  }
}
